package com.power.sifa.aop.controller;

import com.plf.common.domain.ResponseDTO;
import com.power.sifa.aop.api.SMFeign;
import com.power.sifa.aop.service.SMService;
import com.power.sifa.correction.dao.Crc_personDao;
import com.power.sifa.correction.model.Crc_person;
import com.power.sifa.correction.service.Crc_personService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;


@Slf4j
@RestController
public class SMController implements SMFeign {

    @Resource
    private SMService service;

    @Resource
    private Crc_personService crcPersonService;

    @Resource
    private Crc_personDao crcPersonDao;

//    @Value("${sm4.key}")
//    private String key;

    @Override
    public void testCardNoIndex() {
        List<Crc_person> personList = crcPersonDao.findAll();
//        Crc_person person = crcPersonService.findPersonById(id);
        try {
            for (Crc_person person : personList) {
                String cardno = person.getCardno();
                if (StringUtils.isEmpty(cardno) || cardno.length() < 4 || cardno.length() > 18) {
                    log.error("身份证号码[{}]不符合规范", cardno);
                    continue;
                }
                person.setCardno(this.service.encrypt(cardno));
                person.setCardnoIndex(cardno.substring(cardno.length() - 4));
                crcPersonService.saveOrUpdate(person);
                log.warn("修改成功!!!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public ResponseDTO decrypt(String text) {
        Assert.notNull(text, "text参数不能为空");
        try {
            String result = this.service.decrypt(text);
            return ResponseDTO.succData(result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("/sm/decrypt 解密失败->  msg[{}]", e.getMessage());
            return ResponseDTO.wrap(500, e.getMessage());
        }
    }

    @Override
    public ResponseDTO encrypt(String text) {
        Assert.notNull(text, "text参数不能为空");
        try {
            String result = this.service.encrypt(text);
            return ResponseDTO.succData(result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("/sm/decrypt 加密失败->  msg[{}]", e.getMessage());
            return ResponseDTO.wrap(500, e.getMessage());
        }
    }

    @Override
    public ResponseDTO getKey() {
        return ResponseDTO.succData(this.service.getKey());
    }
}
